/*
 * Copyright 2006 Matt Jensen
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.spectaql.internal.jpa;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.spectaql.internal.hibernate.HibernateUtils;
import org.spectaql.jpa.JpaProviderAdapter;
import org.spectaql.metadata.PersistenceMetadata;

/**
 * <p>
 * <code>HibernateJpaProviderAdapter</code> is ...
 * </p>
 */
public class HibernateJpaProviderAdapter implements JpaProviderAdapter
{
    private static Log LOG = LogFactory.getLog(HibernateJpaProviderAdapter.class);

    /**
     * <p>
     * Construct a {@link HibernateJpaProviderAdapter} instance.
     * </p>
     */
    public HibernateJpaProviderAdapter()
    {
        super();
    }

    /* inherit javadoc */
    public PersistenceMetadata getPersistenceMetadata(final Object delegate)
    {
        // Verify that we were passed a Hibernate session delegate.
        if (!(delegate instanceof Session))
        {
            throw new IllegalStateException(String.format("Persistence delegate [%s] does not implement [%s].", 
                    delegate, Session.class));
        }
        final Session session = (Session)delegate;

        // At this point we can proceed as if we were dealing with Hibernate directly (cuz we are.)
        final PersistenceMetadata result = HibernateUtils.createPersistenceMetadata(session);
        if (LOG.isDebugEnabled())
        {
            LOG.debug(String.format("Returning persistence metadata [%s] from session delegate [%s].", result,
                    session));
        }
        return result;
    }
}
